package xgin

import (
	"path/filepath"
	"strings"
)

func Routes() []*RouteInfo {
	rows := engine.Routes()
	result := make([]*RouteInfo, 0)
	for _, v := range rows {
		r, ok := routeMap[v.Path+"|"+strings.ToUpper(v.Method)]
		if ok {
			r.realPath = v.Path
			r.method = v.Method
			r.handler = v.Handler
		} else {
			r = &RouteInfo{
				method:   v.Method,
				realPath: v.Path,
				handler:  v.Handler,
			}
		}
		result = append(result, r)
	}
	return result
}

func Route(path, method string) *RouteInfo {
	if len(path) == 0 {
		return nil
	}

	rows := Routes()
	for _, v := range rows {
		if strings.ToUpper(v.Method()) == strings.ToUpper(method) && v.RealPath() == path {
			return v
		}
	}

	return nil
}

type RouteInfo struct {
	Name     string `json:"name"`
	Path     string `json:"path"`
	Ext      any    `json:"ext"`
	baseName string
	basePath string
	method   string
	realPath string
	handler  string
}

var routeMap = make(map[string]*RouteInfo)

func (info *RouteInfo) BasePath() string {
	return info.basePath
}

func (info *RouteInfo) BaseName() string {
	return info.baseName
}

func (info *RouteInfo) RealPath() string {
	if info.realPath != "" {
		return info.realPath
	}

	return filepath.Join(info.basePath, info.Path)
}

func (info *RouteInfo) HandlerName() string {
	return info.handler
}

func (info *RouteInfo) Method() string {
	return info.method
}
